class PageController < ApplicationController
  layout 'temporary'

  def index
    # 进入login页面有几个区别形式
    # 1、首次登录， 带入epg_info，
    # /?epg_info=%3Cserver_ip%3Ehttp%3A%2F%2F121.60.16.244%3A8080%2Fiptvepg%3C%2Fserver_ip%3E%3Cgroup_name%3E63%3C%2Fgroup_name%3E%3Cgroup_path%3E%2Fiptvepg%2Fframe223%3C%2Fgroup_path%3E%3Coss_user_id%3Ehbgd7%3C%2Foss_user_id%3E%3Cpage_url%3Ehttp%3A%2F%2F121.60.16.244%3A8080%2Fiptvepg%2Fframe223%2Fportal.jsp%3C%2Fpage_url%3E%3Cpartner%3EZTE2X%3C%2Fpartner%3E%3Carea_id%3E11%3C%2Farea_id%3E%3Cback_url%3Ehttp%3A%2F%2F116.210.255.131%3A80%2Ffrontend61%2F%2Fhomepage%2Fhome.htm%3FcCode%3D129%26cpId%3D201%26uid%3D136567%26backDiv%3DtuijianIcon0%3C%2Fback_url%3E
    # 2、订购：订购之前将正在观看的页面存入cookie中，跳转订购后，再回到应用，需要识别Result params，改写orderType, 返回到之前的页面
    logger.info "epg_info==================, #{params[:epg_info]}"
    @order_type = 'free'
    if params[:epg_info]
      epg_info = params[:epg_info]
      @epg_back_url = if Rails.env.development?
                        ENV.fetch("EPG_BACK_URL") { "/recommend" }
                      elsif Rails.env.staging?
                        ENV.fetch("EPG_BACK_URL") { "http://116.210.255.131/frontend61/testPage/home.htm?uid=21" }
                      else
                        ENV.fetch("EPG_BACK_URL") { epg_info.split('<back_url>')[1].split('</back_url>')[0] }
                      end
      @platform = epg_info.split('<partner>')[1].split('</partner>')[0]
      @target_url = order_auth_path
      
      # 如果是要点播单曲
      @code = params[:code]
    else
      redirect_to ENV.fetch("DEFAULT_PATH") { "/recommend" }
    end
  end

  def order_authenticate
    request_authentication
  end

  def to_order
    user_id = cookies[:UserID]
    user_token = cookies[:UserToken]
    user_token = user_token.gsub(/[<%=>]/, "")
    user_platform = cookies[:platform].include? 'HUAWEI' ? 1 : 0
    sp_no = ENV['SP_NO']
    product_id = ENV['PRODUCT_ID']
    timestamp = Time.zone.now.to_formatted_s(:number)
    signature = Digest::MD5.hexdigest(user_id + timestamp + product_id + ENV['SECRET'])

    return_url = if params[:original_fullpath]
                   ERB::Util.url_encode(order_result_url + "?original_fullpath=#{params[:original_fullpath]}")
                 else
                   ERB::Util.url_encode(order_result_url + "?path=#{params[:path]}&id=#{params[:id]}&play_type=#{params[:play_type]}&song_id=#{params[:song_id]}&second_prev=#{params[:second_prev]}")
                 end

    url = "#{ENV['MUSIC_HALL_HOST']}/uniorder.jsp?userId=#{user_id}&userToken=#{user_token}&userPlatform=#{user_platform}&spNo=#{sp_no}&productId=#{product_id}&timeStamp=#{timestamp}&signature=#{signature}&returnUrl=#{return_url}"

    # 开发环境直接跳去根路由
    redirect_to Rails.env.development? ? root_url : url
  end

  def order_result
    # 从一级订购页面返回, 没有 Result, 从二级订购页面, 不论是否订购成功, 都会含有 Result 参数, 不能使用 Result 作为订购是否成功的依据, 得使用鉴权接口
    logger.info "返回结果==================, #{params}"
    # 重新鉴权
    request_authentication
    @target_url = if params[:original_fullpath]
                    params[:original_fullpath]
                  elsif params[:path]
                    "#{params[:path]}?id=#{params[:id]}&play_type=#{params[:play_type]}&song_id=#{params[:song_id]}&second_prev=#{params[:second_prev]}"
                  else
                    ENV.fetch("DEFAULT_PATH") { "/recommend" }
                  end
    if Rails.env.development?
      @platform = 'HUAWEI'
    else
      @platform = cookies[:platform]
    end
    render 'index'
  end

  def no_valid
  end

  def epg_back_url
    redirect_to cookies[:epg_back_url]
  end

  private

    def request_authentication
      user_id = cookies[:UserID]
      user_token = cookies[:UserToken]
      # 给user_token做个容错, 有时候传过来莫名其妙的值, 比如 "<%=ZwXkmWJTCt9IjuQcRSzrYUM433254422%>"
      user_token = user_token.gsub(/[<%=>]/, "")
      user_platform = cookies[:platform].include? 'HUAWEI' ? 1 : 0
      sp_no = ENV['SP_NO']
      product_id = ENV['PRODUCT_ID']
      timestamp = Time.zone.now.to_formatted_s(:number)
      signature = Digest::MD5.hexdigest(user_id + timestamp + product_id + ENV['SECRET'])
      url = "#{ENV['MUSIC_HALL_HOST']}/orderauth.jsp?userId=#{user_id}&userToken=#{user_token}&userPlatform=#{user_platform}&spNo=#{sp_no}&productId=#{product_id}&timeStamp=#{timestamp}&signature=#{signature}"

      logger.info "cookies==================, #{cookies.to_h}"
      logger.info "url==================, #{url}"

      @order_type = "free"
      unless Rails.env.development?
        # 开发环境不请求, 直接赋值
        # url = "http://116.210.255.159:21303/music-hall/order/orderauth.jsp?userId=hwhbgd9&userToken=jOU6mN_vvrX3utLoIokyWUo516276810&userPlatform=1&spNo=HBGD_QQ&productId=gdhdlgf1&timeStamp=20210406123019&signature=a95c687a5337a91d964b8f79ddbcb9cb"
        response = RestClient.get(url, headers = {})
        if response && response.code == 200 && response.body
          body = JSON.parse(response)
          logger.info "body==================, #{body}"

          if body["Result"] == 0
            @order_type = body["orderType"]
            # @order_type 是 "month" 或者 "free"
          end
        end
      end
    end
end
